//
//  RootViewController.m
//  UI15_网络编程
//
//  Created by dllo on 15/11/27.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RootViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface RootViewController ()<NSURLSessionDownloadDelegate>
@property (retain, nonatomic) IBOutlet UIButton *postB;
@property (retain, nonatomic) IBOutlet UIButton *getB;
@property (retain, nonatomic) IBOutlet UIButton *downImageB;
@property (retain, nonatomic) IBOutlet UIImageView *ImageV;
@property (retain, nonatomic) IBOutlet UIButton *downMovieB;
@property (retain, nonatomic) IBOutlet UIProgressView *progressV;
@property (retain, nonatomic) IBOutlet UIButton *suspendB;
@property (retain, nonatomic) IBOutlet UIButton *continueB;
@property (retain, nonatomic) NSURLSessionDownloadTask *downMovieT;

@end

@implementation RootViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    
}
- (IBAction)downImageAction:(UIButton *)sender {
    
    NSURL *url = [NSURL URLWithString:@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDownloadTask *downImageT = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        
        NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        // 拼接文件名 - 推荐用系统推荐的文件名(与服务器文件同名), 也可自定义文件名
        // 自定义文件名
//        NSString *file = [cach stringByAppendingPathComponent:@"wangning.png"];
        
        // 系统推荐文件名
        NSString *file = [cach stringByAppendingPathComponent:response.suggestedFilename];
        
        // 管理文件的类
        NSFileManager *fileM = [NSFileManager defaultManager];
        
        // 将下载数据有临时文件搬到自己的缓存路径内
        [fileM moveItemAtPath:location.path toPath:file error:nil];
        
        self.ImageV.image = [UIImage imageWithContentsOfFile:file];
        
    }];
    
    [downImageT resume];
    
}

// 创建播放器并播放
- (void)playWithFilePath:(NSString *)filePath
{
    
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    AVPlayer *player = [AVPlayer playerWithURL:url];
    
    // 用来显示视频
    AVPlayerLayer *playerL = [AVPlayerLayer playerLayerWithPlayer:player];
    // 设置视频位置及大小
    playerL.frame = CGRectMake(50, 500, 300, 200);
    // 添加
    [self.view.layer addSublayer:playerL];
    
    // 开始播放
    [player play];

}

// 下载大文件
- (IBAction)downMovieAction:(UIButton *)sender {
    
    // 若已经存在任务则不再触发, 直接退出返回
    if (nil != self.downMovieT) {
        return;
    }
    
    NSURL *url = [NSURL URLWithString:@"http://hc25.aipai.com/user/656/20448656/6167672/card/25033081/card.mp4?l=a"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 协议代理方式进行请求
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    // 创建下载任务
    self.downMovieT = [session downloadTaskWithRequest:request];
    
    
    //开始任务
    [_downMovieT resume];
    
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{

    NSLog(@"下载完毕后调用");
    
    NSString *cach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    // 自定义名字
//    NSString *file = [cach stringByAppendingPathComponent:@"wangning.mp4"];
    
    // 系统建议名字
    NSString *file = [cach stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    
    [self playWithFilePath:file];
    
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    NSLog(@"下载过程中会多次调用, 每次下载不一定多大的数据");
    NSLog(@"本次下载大小:%lldKB, 已经下载大小:%lldKB, 总大小:%lldKB", bytesWritten / 1024, totalBytesWritten / 1024, totalBytesExpectedToWrite / 1024);
    
    
    self.progressV.progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
    
    
    
    
    
}
- (IBAction)continueAction:(UIButton *)sender {
    
    
    if (NSURLSessionTaskStateSuspended == self.downMovieT.state) {
        // 继续下载
        [self.downMovieT resume];
    }

    
}


- (IBAction)suspendAction:(UIButton *)sender {
    
    if (NSURLSessionTaskStateRunning == self.downMovieT.state) {
        // 暂停下载
        [self.downMovieT suspend];
    }

    
}



- (IBAction)getAction:(UIButton *)sender {
    
    // 5, 网址字符串
    NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
    
    // 6, IOS9.0后使用的未明字符转换, 未明字符如中文
    NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 4, 创建url
    NSURL *url = [NSURL URLWithString:urlEncode];
    
    // 3, 创建请求对象, request可设置信息如:url, 方式(GET/POST), 超时时间等
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 1, 创建NSURLSession对象, 选择默认配置
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    // 2, 创建请求任务, 当异步请求完成会调用block, 在block内完成数据处理
    NSURLSessionDataTask *getTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        // 当数据请求完毕, 在此处解析数据
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dic);
        
    }];
    
    // 7, 开始任务
    [getTask resume];
    
}


- (IBAction)postAction:(UIButton *)sender {
    
    NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    
    /*************************POST新增*****************************/
    
    // 先设置为POST模式
    request.HTTPMethod = @"POST";
    
    NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
    
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    // 再添加Body
    request.HTTPBody = bodyData;
    
    
    /***************************************************************/
    
    NSURLSessionDataTask *postT = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", result);
        
    }];
    
    [postT resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)dealloc {
    [_postB release];
    [_getB release];
    [_downImageB release];
    [_ImageV release];
    [_downMovieB release];
    [_progressV release];
    [_suspendB release];
    [_continueB release];
    [_downMovieT release];
    [super dealloc];
}
@end
